package com.omni.monitor.plugin.threadpool;

import com.omni.monitor.plugin.trace_monitor.AutoCleanTtlThreadPoolDecorator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Spring Bean后置处理器：自动装饰所有ThreadPoolExecutor类型的Bean
 * 无需修改原有线程池调用代码，实现无侵入增强
 */
@Component
@Slf4j
public class TtlThreadPoolBeanPostProcessor implements BeanPostProcessor {

    @Resource
    ThreadPoolMonitor threadPoolMonitor ;
    /**
     * Bean初始化后调用：如果是ThreadPoolExecutor，自动用装饰器包装
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 只处理ThreadPoolExecutor及其子类（如ScheduledThreadPoolExecutor需额外处理）
        if (bean instanceof ThreadPoolExecutor && !(bean instanceof AutoCleanTtlThreadPoolDecorator)) {
            ThreadPoolExecutor originalExecutor = (ThreadPoolExecutor) bean;
            // 用装饰器包装原始线程池
            AutoCleanTtlThreadPoolDecorator decoratedExecutor = new AutoCleanTtlThreadPoolDecorator(originalExecutor);
            threadPoolMonitor.register(beanName, decoratedExecutor);
            log.info("线程池Bean[{}]已自动装饰为AutoCleanTtlThreadPool，支持上下文自动清理", beanName);
            return decoratedExecutor; // 返回装饰后的线程池，替换原始Bean
        }
        // 非线程池Bean直接返回
        return bean;
    }

    /**
     * Bean初始化前调用：无需处理
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
